/**
 * JAVACC DEMO 1.0
 */
package com.apache.client.servlet;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.apache.api.vo.ResultMsg;
import com.apache.client.InfoReleaseCoreCleint;
import com.apache.database.model.Page;
import com.apache.info.entity.PubMetadata;
import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.ToolsUtil;

import net.sf.json.JSONObject;

/**
 * description: 单表/主子表客户端action
 * doCode=Add:添加信息; doCode=Edit:修改信息; doCode=Del:删除信息;
 * doCode=List:查信息列表(pageSize,pageIndex赋值则分页); doCode=Count:查单表数量;
 * doCode=:查信息详细(需要传sortCode及信息ID); doCode=Ssave:添加主子表信息; doCode=Sedit:修改主子表信息;
 * doCode=Sdel:删除主子表信息; doCode=Slist:查主子表信息列表(pageSize,pageIndex赋值则分页);
 * doCode=Scount:查主子表信息数量; doCode=Sview:查看主子表信息详细;doCode=CountAll:信息总记录数
 *
 * @author Hou Dayu 创建时间：2016-8-11
 */
@SuppressWarnings("serial")
public class InfoReleaseClientAction extends InfoReleaseActionSupport {

	private Logger logger = Logger.getLogger(getClass().getName());

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String doCode = request.getParameter("doCode");
		if (StrUtil.isNull(doCode)) {
			defaultMethod(request, response);
			return;
		}
		try {
			Method method = InfoReleaseClientAction.class.getDeclaredMethod(doCode,
					new Class[] { HttpServletRequest.class, HttpServletResponse.class });
			method.invoke(this, request, response);
		} catch (Exception e) {
			logger.error(e);
			JSONObject json = new JSONObject();
			json.put("flag", "F");
			json.put("msg", "系统执行异常,请稍后重试");
			outputJson(json.toString(), response);
		}
	}

	//默认方法(按信息ID获取详细信息)
	public void defaultMethod(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Map<String, String> params = this.getRequestMap(request);
		if (ToolsUtil.isNotNull(params.get("sortCode"))) {
			Object favorite = InfoReleaseCoreCleint.getInstance().selectSingle(params);
			JSONObject array = JSONObject.fromObject(favorite);
			outputJson(array.toString(), response);
		}
	}

	//查看主子表信息详细
	public void Sview(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String> params = this.getRequestMap(request);
		Object subobj = InfoReleaseCoreCleint.getInstance().selectMasterSlaveSingle(params);
		JSONObject array = JSONObject.fromObject(subobj);
		outputJson(array.toString(), response);
	}

	//单表信息添加
	public void Add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String> params = this.getRequestMap(request);
		if (ToolsUtil.isNull(params.get("sortCode")))
			return;
		LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
		params.put("createUser", loginUser.getUserEname());
		params.put("createdTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
		ResultMsg result = saveInfo(request, params, params.get("sortCode"));
		JSONObject array = JSONObject.fromObject(result);
		outputJson(array.toString(), response);
	}

	//单表信息修改
	public void Edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String> params = this.getRequestMap(request);
		if (ToolsUtil.isNull(params.get("sortCode")))
			return;
		LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
		params.put("modifyUser", loginUser.getUserEname());
		params.put("modifyTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
		ResultMsg result = editInfo(request, params, params.get("sortCode"));
		JSONObject array = JSONObject.fromObject(result);
		outputJson(array.toString(), response);
	}

	//单表信息删除
	public void Del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String> params = this.getRequestMap(request);
		if (ToolsUtil.isNull(params.get("sortCode")))
			return;
		ResultMsg result = delInfo(request, params, params.get("sortCode"));
		JSONObject array = JSONObject.fromObject(result);
		outputJson(array.toString(), response);
	}

	//主子表信息添加
	public void Ssave(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String> params = this.getRequestMap(request);
		ResultMsg result = saveSubInfo(request, params);
		JSONObject array = JSONObject.fromObject(result);
		outputJson(array.toString(), response);
	}

	//主子表信息修改
	public void Sedit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String> params = this.getRequestMap(request);
		ResultMsg result = editsubInfo(request, params);
		JSONObject array = JSONObject.fromObject(result);
		outputJson(array.toString(), response);
	}

	//主子表信息删除
	public void Sdel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String> params = this.getRequestMap(request);
		ResultMsg result = delSubInfo(request, params);
		JSONObject array = JSONObject.fromObject(result);
		outputJson(array.toString(), response);
	}

	//查询单表信息列表
	public void List(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String> params = this.getRequestMap(request);
		Map<String, Object> map = new HashMap<String, Object>();
		String pageSize = StrUtil.doNull(params.get("pageSize"), params.get("rows"));
		if (ToolsUtil.isNotNull(pageSize)) {
			String pageIndex = StrUtil.doNull(params.get("pageIndex"), params.get("page"));
			params.put("pageIndex", StrUtil.doNull(pageIndex, "1"));
			params.put("pageSize", pageSize);
			Page page = (Page) InfoReleaseCoreCleint.getInstance().selectInfo(params);
			map.put("pageSize", page.getPageSize());
			map.put("pageIndex", page.getPageNeeded());
			map.put("total", page.getCount());
			map.put("rows", page.getPageObjects());
		} else {
			Object favoritePage = InfoReleaseCoreCleint.getInstance().selectInfo(params);
			if (null == favoritePage) {
				map.put("total", "0");
			} else {
				map.put("total", ((List) favoritePage).size());
			}
			map.put("rows", favoritePage);
		}
		JSONObject array = JSONObject.fromObject(map);
		outputJson(array.toString(), response);
	}

	//查询主子表信息列表
	public void Slist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String> params = this.getRequestMap(request);
		Map<String, Object> map = new HashMap<String, Object>();
		String pageSize = StrUtil.doNull(params.get("pageSize"), params.get("rows"));
		if (ToolsUtil.isNotNull(pageSize)) {
			String pageIndex = StrUtil.doNull(params.get("pageIndex"), params.get("page"));
			params.put("pageIndex", StrUtil.doNull(pageIndex, "1"));
			Page page = (Page) InfoReleaseCoreCleint.getInstance().selectMasterSlaveInfo(params);
			map.put("pageSize", page.getPageSize());
			map.put("pageIndex", page.getPageNeeded());
			map.put("total", page.getCount());
			map.put("rows", page.getPageObjects());
		} else {
			Object favoritePage = InfoReleaseCoreCleint.getInstance().selectMasterSlaveInfo(params);
			if (null == favoritePage) {
				map.put("total", "0");
			} else {
				map.put("total", ((List) favoritePage).size());
			}
			map.put("rows", favoritePage);
		}
		JSONObject array = JSONObject.fromObject(map);
		outputJson(array.toString(), response);
	}

	//获取信息总数(createUser,sortId可空)
	public void CountAll(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Map<String, String> params = this.getRequestMap(request);
		LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
		params.put("createUser", loginUser.getUserEname());
		long count = InfoReleaseCoreCleint.getInstance().countStatistics(params);
		outputJson(count + "", response);
	}

	//查询多表记录数
	public void Scount(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String> params = this.getRequestMap(request);
		LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
		params.put("createUser", loginUser.getUserEname());
		long scount = InfoReleaseCoreCleint.getInstance().countMasterSlaveInfo(params);
		outputJson(scount + "", response);
	}

	//查询单表记录数
	public void Count(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String> params = this.getRequestMap(request);
		LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
		params.put("createUser", loginUser.getUserEname());
		long count = InfoReleaseCoreCleint.getInstance().countInfo(params);
		outputJson(count + "", response);
	}

	/**
	 * description:  主子表联插
	 */
	private ResultMsg saveSubInfo(HttpServletRequest request, Map<String, String> params) {
		ResultMsg json = null;
		String tabName = params.get("tabName");
		String sortCodes[] = tabName.split(",");
		List<PubMetadata> list = new ArrayList<PubMetadata>();
		for (int i = 0; i < sortCodes.length; i++) {
			List<PubMetadata> pms = InfoReleaseCoreCleint.getInstance().getMetadatas(sortCodes[i],
					params.get("sysName"));
			if (null != pms)
				list.addAll(pms);
		}
		if (null == list)
			return null;
		LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
		params.put("userOrg", loginUser.getOrgEname());
		params.put("createUser", loginUser.getUserEname());
		params.put("createdTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
		params.put("infoId", UUID.randomUUID().toString().replaceAll("-", ""));
		params.put("subId", params.get("infoId"));
		params.put("mainSortCode", sortCodes[0]);
		params.put("subSortCode", sortCodes[1]);
		params.put("subSortId", sortCodes[1]);
		for (PubMetadata pm : list) {
			if ("6".equals(pm.getDataType()) && "2".equals(pm.getDataRestrict())) {//处理日期类型
				if (StrUtil.isNull(params.get(pm.getDataAttr()))) {
					params.put(pm.getDataAttr(), DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
				}
			} else if ("2".equals(pm.getDataRestrict())) {
				if (StrUtil.isNull(params.get(pm.getDataAttr()))) {
					json = new ResultMsg("F", "表单的必填项不可为空");
					return json;
				}
			}
		}
		json = InfoReleaseCoreCleint.getInstance().saveMasterSlaveInfo(params);
		return json;
	}

	/**
	 * description:  主子表联改
	 */
	private ResultMsg editsubInfo(HttpServletRequest request, Map<String, String> params) {
		ResultMsg json = null;
		String tabName = params.get("tabName");
		String sortCodes[] = tabName.split(",");
		LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
		params.put("mainSortCode", sortCodes[0]);
		params.put("subSortCode", sortCodes[1]);
		params.put("modifyUser", loginUser.getUserEname());
		params.put("modifyTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
		if (StrUtil.isNull(params.get("infoId"))) {//处理主键
			json = new ResultMsg("F", "非空参数不可为空");
			return json;
		}
		params.put("subId", params.get("infoId"));
		json = InfoReleaseCoreCleint.getInstance().updateMasterSlaveInfo(params);
		return json;
	}

	/**
	 * description:  主子表联删
	 */
	private ResultMsg delSubInfo(HttpServletRequest request, Map<String, String> params) {
		ResultMsg json = null;
		String tabName = params.get("tabName");
		String sortCodes[] = tabName.split(",");
		params.put("mainSortCode", sortCodes[0]);
		params.put("subSortCode", sortCodes[1]);
		if (StrUtil.isNull(params.get("infoId"))) {//处理主键
			json = new ResultMsg("F", "非空参数不可为空");
			return json;
		}
		params.put("subId", params.get("infoId"));
		json = InfoReleaseCoreCleint.getInstance().deleteInfo(params);
		return json;
	}
}
